package org.example.controller.platform;

import cn.dev33.satoken.annotation.SaCheckLogin;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.common.result.Result;
import org.example.common.utils.SaTokenUtils;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.mapper.RoleMapper;
import org.example.mapper.UserRolePlatformRelationMapper;
import org.example.service.PermissionService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 平台端「个人中心」接口
 */
@RestController
@RequestMapping("/platform/profile")
@Tag(name = "平台端个人中心", description = "平台端用户个人信息和权限管理")

@Slf4j
public class ProfileController {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private SaTokenUtils saTokenUtils;
    
    @Autowired
    private UserRolePlatformRelationMapper userRolePlatformRelationMapper;

    /**
     * 基础信息卡片：头像、姓名、手机号、角色名、状态等
     */
    @SaCheckLogin
    @GetMapping("/info")
    @Operation(summary = "获取个人信息", description = "获取当前登录用户的基础信息")
    public Result<Map<String, Object>> getProfileInfo() {
        try {
            Long userId = saTokenUtils.getCurrentUserId();
            String userType = saTokenUtils.getCurrentUserType();
            String token = saTokenUtils.getTokenValue();
            
            log.info("=== ProfileController.getProfileInfo 调试 ===");
            log.info("获取到的用户ID: {}", userId);
            log.info("获取到的用户类型: {}", userType);
            log.info("当前token: {}", token);
            log.info("当前登录ID: {}", saTokenUtils.getSessionId());

            
            if (userId == null) {
                return Result.unauthorized("未登录");
            }

            User user = userService.getById(userId);
            log.info("查询到的用户: {}", user);
            if (user != null) {
                log.info("数据库中的用户类型: {}", user.getUserType());
                log.info("用户状态: {}", user.getStatus());
            }
            
            if (user == null || user.getUserType() == null || !"平台端".equals(user.getUserType())) {
                log.error("用户验证失败 - user: {}, userType: {}, sessionUserType: {}", user, user != null ? user.getUserType() : "null", userType);
                return Result.forbidden("不是平台端账号");
            }

            // 仅以平台关联表为准，取第一条关联的角色
            Long roleId = null;
            try {
                java.util.List<Long> roleIds = userRolePlatformRelationMapper.getRoleIdsByUserId(userId);
                if (roleIds != null && !roleIds.isEmpty()) {
                    roleId = roleIds.get(0);
                }
            } catch (Exception ignore) {}
            String roleName = null;
            if (roleId != null) {
                Role role = roleMapper.selectById(roleId);
                if (role != null) roleName = role.getRoleName();
            }

            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("realName", user.getRealName());
            data.put("phone", user.getPhone());
            data.put("avatarUrl", user.getAvatarUrl());
            data.put("roleId", roleId);
            data.put("roleName", roleName);
            data.put("status", user.getStatus());
            data.put("statusText", user.getStatus() == null ? "未知" : (user.getStatus() == 1 ? "启用" : "禁用"));
            data.put("createdAt", user.getCreatedAt());
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户资料失败", e);
            return Result.error("获取用户资料失败：" + e.getMessage());
        }
    }

    /**
     * 权限信息表格：返回权限码列表，前端按模块/栏目展示
     */
    @SaCheckLogin
    @GetMapping("/permissions")
    @Operation(summary = "获取个人权限", description = "获取当前登录用户的权限信息")
    public Result<Map<String, Object>> getMyPermissions() {
        try {
            Long userId = saTokenUtils.getCurrentUserId();
            if (userId == null) {
                return Result.unauthorized("未登录");
            }

            List<String> permissionCodes = permissionService.getPlatformPermissionsByUserId(userId);
            // 同时返回中文名称映射（仅保留当前用户拥有的权限）
            Map<String, String> allMap = permissionService.getPermissionMap();
            Map<String, String> permissionMap = new java.util.HashMap<>();
            if (permissionCodes != null && allMap != null) {
                for (String code : permissionCodes) {
                    String name = allMap.get(code);
                    if (name != null) permissionMap.put(code, name);
                }
            }

            Map<String, Object> data = new HashMap<>();
            data.put("permissionCodes", permissionCodes);
            data.put("permissionMap", permissionMap);
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取个人权限失败", e);
            return Result.error("获取个人权限失败");
        }
    }

    /**
     * 换绑手机号（无需 userId，取当前登录用户）
     * body: { oldPhone, oldCode, newPhone, newCode }
     */
    @SaCheckLogin
    @PostMapping("/change-phone")
    @Operation(summary = "换绑手机号", description = "换绑当前登录用户的手机号")
    public Result<String> changeMyPhone(@RequestBody Map<String, String> body) {
        try {
            Long userId = saTokenUtils.getCurrentUserId();
            if (userId == null) {
                return Result.unauthorized("未登录");
            }

            String oldPhone = body.get("oldPhone");
            String oldCode = body.get("oldCode");
            String newPhone = body.get("newPhone");
            String newCode = body.get("newCode");
            if (oldPhone == null || oldCode == null || newPhone == null || newCode == null) {
                return Result.badRequest("参数不完整");
            }

            userService.changePlatformUserPhone(userId, oldPhone, oldCode, newPhone, newCode);
            return Result.success("换绑成功");
        } catch (Exception e) {
            log.error("换绑手机号失败", e);
            return Result.error("换绑失败: " + e.getMessage());
        }
    }
}


